package com.example.lightenergypolymerize.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.lightenergypolymerize.entity.Answer;
import com.example.lightenergypolymerize.entity.enums.AiModelEnum;
import com.example.lightenergypolymerize.entity.enums.AiTypeEnum;
import com.example.lightenergypolymerize.service.IAnswerService;
import com.example.lightenergypolymerize.util.AppVariable;
import com.example.lightenergypolymerize.util.ResponseEntity;
import com.example.lightenergypolymerize.util.SecurityUtil;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
//import org.springframework.ai.openai.OpenAiChatModel;
//import org.springframework.ai.openai.OpenAiImageModel;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.baomidou.mybatisplus.extension.toolkit.Db.list;

@RestController
@RequestMapping("/openai")
public class OpenAIController {
    @Resource
    private OpenAiChatClient chatModel;

//    @Resource
//    private OpenAiImageModel imageModel;

    @Resource
    private IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/chat")
    public ResponseEntity chat(String question){
        if(!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("请先输入内容");
        }

        String result = "";//大模型返回的结果
        boolean addResult = false;//数据是否添加到了数据库
        //执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(), AiTypeEnum.CHAT.getValue());
        //1.获取分布式锁示例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            //2.获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                //获取分布式锁失败
                return ResponseEntity.fail("请勿频繁调用接口");
            }
            result = chatModel.call(question);
            //将结果保存到数据库
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.OPENAI.getValue());
            answer.setType(AiTypeEnum.CHAT.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            addResult = answerService.save(answer);
        }catch (Exception e) {
        }finally {
            //3.释放分布式锁
            rLock.unlock();
        }
        if(addResult) {
            return ResponseEntity.succ(result);
        }
        return ResponseEntity.fail("数据保存失败，请重试！");
    }





//    @RequestMapping("/draw")
//    public ResponseEntity draw(String question){
//        if(!StringUtils.hasLength(question)) {
//            return ResponseEntity.fail("请先输入内容");
//        }
//        ImageResponse result = imageModel.call(new ImagePrompt(question));
//        return ResponseEntity.succ(result.getResults().get(0));
//    }

    @RequestMapping("/getchatlist")
    public ResponseEntity getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int type = AiTypeEnum.CHAT.getValue();
        int model = AiModelEnum.OPENAI.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model, type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if(list == null) {//缓存不存在
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("type", type);
            queryWrapper.eq("model", model);
            //可以通过时间来排序也可以通过主键aid来排序，用主键aid来排序查询速度快,因为主键添加了索引
            queryWrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(queryWrapper);
            //查出数据存储到缓存中
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        }
        return ResponseEntity.succ(list);
    }


}
